import * as React from 'react';

const DrawCtx = React.createContext();
DrawCtx.displayName = 'DrawCtx';

function drawReducer(state, action) {
  console.log(action);
  switch (action.type) {
    case 'add': {
      return {
        ...state,
        ...action.payload,
      };
    }
    case 'remove': {
      let { [action.payload.id]: removeProp, ...rest } = state;
      return rest;
    }
    default: {
      throw new Error(`没有规定的action类型: ${action.type}`);
    }
  }
}

export function DrawProvider({ children }) {
  const [state, dispatch] = React.useReducer(drawReducer, {});
  const value = [state, dispatch];
  return <DrawCtx.Provider value={value}>{children}</DrawCtx.Provider>;
}

export function useDrawStore() {
  const context = React.useContext(DrawCtx);
  if (context === undefined) {
    throw new Error(`useDrawStore 必须配合 DrawProvider使用`);
  }
  return context;
}
